import React from 'react'
import style from './ShoppingCart.module.css'
import { MainLayout } from '../../layouts/mainLayout'
import { 
  Row,
  Col,
  Affix
} from 'antd'
import { ProductList, PaymentCard } from '../../components' 
import { useSelector } from '../../redux/hooks'
import { useDispatch } from 'react-redux'
import { clearShoppingCartItem, checkout } from '../../redux/shoppingCart/slice'
import { useNavigate } from 'react-router-dom' 

export const ShoppingCart: React.FC = () => {

  const loading = useSelector(s => s.shoppingCart.loading)
  const shoppingCartItems = useSelector(s => s.productSearch.data)
  const jwt = useSelector(s => s.user.token) as string
  const dispatch = useDispatch()
  const navigate = useNavigate()
  console.log(shoppingCartItems, 'shoppingCartItemss')
  return (
    <MainLayout>
      <Row>
        {/* 购物车清单 */}
        <Col span={16}>
          <div className={style['product-list-container']}>
            <ProductList data={shoppingCartItems}></ProductList>
          </div>
        </Col>
        {/* 支付卡组件 */}
        <Col span={8}>
          {/* 页面滑动是支付卡组件固定不动,需要使用Affix锚点组件包裹 */}
          <Affix>
            <div className={style['payment-card-container']}>
              <PaymentCard 
                loading={loading}
                originalPrice={shoppingCartItems.map(s => s.originalPrice).reduce((a, b) => a+ b, 0)}
                price={shoppingCartItems.map(s => s.originalPrice * s.discountPresent ? s.discountPresent : 1).reduce((a, b) => a+ b, 0)}
                onCheckout={() => {
                  if(shoppingCartItems.length <= 0) {
                    return
                  }
                  dispatch(checkout(jwt))
                  navigate('/placeOrder')
                }}
                onShoppingCartClear={() => {
                  dispatch(clearShoppingCartItem({jwt, itemIds: shoppingCartItems.map( s => s.id)}))
                }}
              ></PaymentCard>
            </div>
          </Affix>
        </Col>
      </Row>
    </MainLayout>
  )
}
